// pages/search/search.js
import ajax from '../../requests/ajax.js'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    inputShowed: false,
    inputVal: "",
    hotSearch: [],
    resultl: [],
    hasResult: false,
    isEnd: false,
    start: 0,
    localSearch: wx.getStorageSync('search') || []
  },
  clearInput () {
    this.setData({
      inputVal: "",
      hasResult: false,
      localSearch: wx.getStorageSync('search') || []
    });
  },
  inputTyping (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },
  doSearch() {
    let localSearch = wx.getStorageSync('search') || []

    const isInLocal = localSearch.some((item) => {
      return item.word === this.data.inputVal
    })

    if(isInLocal) {
      localSearch = localSearch.map(item => {
        if(item.word === this.data.inputVal) {
          item.times += 1
        }
        return item
      })
    } else{
      localSearch.push({
        word: this.data.inputVal,
        times: 1
      })
    }
    wx.setStorageSync('search', localSearch)

    ajax.get(`/api/search?word=${this.data.inputVal}&start=${this.data.start}&sort=0&couponOnly=NaN&minPrice=0&maxPrice=99999`)
      .then(res => {
        const resultl = this.data.resultl.concat(res.data.data.list)
        const start = res.data.data.nextIndex
        const isEnd = res.data.data.isEnd
        if(res.data.code === 200) {
          this.setData({
            hasResult: true,
            resultl,
            start,
            isEnd
          })
        }
      })
  },
  onKeyWords(e) {
    this.setData({
      inputShowed: true,
      inputVal: e.currentTarget.dataset.value
    }, () => {
      this.doSearch()
    })
  },
  getHotSearch() {
    ajax.get('/api/search/home')
      .then(res => {
        if (res.data.code === 200) {
          this.setData({
            hotSearch: res.data.data.hotWords.slice(1)
          })
        }
      })
  },
  handleDeleteStorage(){
    wx.removeStorageSync('search')
    this.setData({
      localSearch: wx.getStorageSync('search') || []
    })
  },
  loadMore(){
    this.doSearch()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getHotSearch()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})